code source game Bi-a 3D

23.672 lượt xem;
1 using UnityEngine;
2
3 namespace
ThreeDPool
4 {
5     
public class Singleton<T> : MonoBehaviour where T : Singleton<T>
6     {
7         
private static GameObject _instanceGO;
8         
private static T _instance;
9         
10         
public static T Instance
11         {
12             
get
13             {
14                 
if (_instance == null)
15                 {
16                     
string typeName = typeof(T).Name;
17
18                     
// find the object name
19                     _instanceGO = GameObject.Find(typeName);
20                     _instance = _instanceGO.GetComponent<T>();
21
22                     
// making sure that there is only one object of this type at anytime
23                     
if (_instanceGO == null && _instance == null)
24                     {
25                         
// create an empty gameobject
26                         _instanceGO =
new GameObject();
27
28                         
// track the object by its type name
29                         _instanceGO.name = typeName;
30
31                         
// create singleton object
32                         _instance = _instanceGO.AddComponent<T>();
33                     }
34
35
36                     
// this makes sure that there is only one object of this type
37                     
// lifetime of this object is the application lifetime
38                     GameObject.DontDestroyOnLoad(_instanceGO);
39                 }
40
41                 
return _instance;
42             }
43         }
44
45         
protected virtual void Init()
46         {
47
48         }
49
50         
protected virtual void Awake()
51         { }
52
53         
protected virtual void Start()
54         { }
55
56         
protected virtual void Update()
57         { }
58
59         
protected virtual void OnDestroy()
60         {
61             _instanceGO =
null;
62             _instance =
null;
63         }
64
65     }
66 }


Gõ tìm kiếm nhanh...